// 布局状态管理
// 管理编辑器的整体布局状态，包括侧边栏、面板、主题等

import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { persist } from 'zustand/middleware';

// 侧边栏位置枚举
export enum SidebarPosition {
  Left = 'left',
  Right = 'right'
}

// 面板位置枚举
export enum PanelPosition {
  Bottom = 'bottom',
  Right = 'right'
}

// 主题枚举
export enum Theme {
  Light = 'light',
  Dark = 'dark',
  Auto = 'auto'
}

// 面板类型枚举
export enum PanelType {
  Terminal = 'terminal',
  Problems = 'problems',
  Output = 'output',
  Debug = 'debug',
  Search = 'search'
}

// 侧边栏视图类型枚举
export enum SidebarViewType {
  Explorer = 'explorer',
  Search = 'search',
  SourceControl = 'source-control',
  Extensions = 'extensions',
  Graph = 'graph'
}

// 布局配置接口
export interface LayoutConfig {
  // 侧边栏配置
  sidebar: {
    isVisible: boolean;
    position: SidebarPosition;
    width: number;
    activeView: SidebarViewType;
    isCollapsed: boolean;
  };
  
  // 底部面板配置
  panel: {
    isVisible: boolean;
    position: PanelPosition;
    height: number;
    width: number; // 当面板在右侧时使用
    activeTab: PanelType;
    tabs: PanelType[];
  };
  
  // 主编辑器区域配置
  editor: {
    showMinimap: boolean;
    showLineNumbers: boolean;
    wordWrap: boolean;
    fontSize: number;
    tabSize: number;
  };
  
  // 主题配置
  theme: {
    current: Theme;
    followSystem: boolean;
  };
  
  // 窗口配置
  window: {
    isMaximized: boolean;
    isFullscreen: boolean;
    width: number;
    height: number;
    x: number;
    y: number;
  };
  
  // 工具栏配置
  toolbar: {
    isVisible: boolean;
    items: string[];
  };
  
  // 状态栏配置
  statusBar: {
    isVisible: boolean;
    items: string[];
  };
}

// 布局状态接口
export interface LayoutState extends LayoutConfig {
  // 动作方法
  // 侧边栏操作
  toggleSidebar: () => void;
  setSidebarVisible: (visible: boolean) => void;
  setSidebarPosition: (position: SidebarPosition) => void;
  setSidebarWidth: (width: number) => void;
  setSidebarActiveView: (view: SidebarViewType) => void;
  toggleSidebarCollapse: () => void;
  
  // 面板操作
  togglePanel: () => void;
  setPanelVisible: (visible: boolean) => void;
  setPanelPosition: (position: PanelPosition) => void;
  setPanelHeight: (height: number) => void;
  setPanelWidth: (width: number) => void;
  setPanelActiveTab: (tab: PanelType) => void;
  addPanelTab: (tab: PanelType) => void;
  removePanelTab: (tab: PanelType) => void;
  
  // 编辑器操作
  setEditorConfig: (config: Partial<LayoutConfig['editor']>) => void;
  
  // 主题操作
  setTheme: (theme: Theme) => void;
  toggleTheme: () => void;
  setFollowSystem: (follow: boolean) => void;
  
  // 窗口操作
  setWindowConfig: (config: Partial<LayoutConfig['window']>) => void;
  toggleMaximize: () => void;
  toggleFullscreen: () => void;
  
  // 工具栏操作
  toggleToolbar: () => void;
  setToolbarItems: (items: string[]) => void;
  
  // 状态栏操作
  toggleStatusBar: () => void;
  setStatusBarItems: (items: string[]) => void;
  
  // 重置布局
  resetLayout: () => void;
  
  // 导入/导出配置
  exportConfig: () => LayoutConfig;
  importConfig: (config: Partial<LayoutConfig>) => void;
}

// 默认布局配置
const defaultLayoutConfig: LayoutConfig = {
  sidebar: {
    isVisible: true,
    position: SidebarPosition.Left,
    width: 320,
    activeView: SidebarViewType.Explorer,
    isCollapsed: false,
  },
  panel: {
    isVisible: false,
    position: PanelPosition.Bottom,
    height: 300,
    width: 400,
    activeTab: PanelType.Terminal,
    tabs: [PanelType.Terminal, PanelType.Problems, PanelType.Output],
  },
  editor: {
    showMinimap: true,
    showLineNumbers: true,
    wordWrap: false,
    fontSize: 14,
    tabSize: 2,
  },
  theme: {
    current: Theme.Auto,
    followSystem: true,
  },
  window: {
    isMaximized: false,
    isFullscreen: false,
    width: 1200,
    height: 800,
    x: 100,
    y: 100,
  },
  toolbar: {
    isVisible: true,
    items: ['new', 'open', 'save', 'undo', 'redo', 'search'],
  },
  statusBar: {
    isVisible: true,
    items: ['line-column', 'encoding', 'language', 'git-branch'],
  },
};

// 创建布局状态管理Store
export const useLayoutStore = create<LayoutState>()(
  subscribeWithSelector(
    persist(
      (set, get) => ({
        ...defaultLayoutConfig,

        // 侧边栏操作
        toggleSidebar: () => {
          set((state) => ({
            sidebar: {
              ...state.sidebar,
              isVisible: !state.sidebar.isVisible,
            },
          }));
        },

        setSidebarVisible: (visible: boolean) => {
          set((state) => ({
            sidebar: {
              ...state.sidebar,
              isVisible: visible,
            },
          }));
        },

        setSidebarPosition: (position: SidebarPosition) => {
          set((state) => ({
            sidebar: {
              ...state.sidebar,
              position,
            },
          }));
        },

        setSidebarWidth: (width: number) => {
          // 限制侧边栏宽度在200-600px之间
          const clampedWidth = Math.max(200, Math.min(600, width));
          set((state) => ({
            sidebar: {
              ...state.sidebar,
              width: clampedWidth,
            },
          }));
        },

        setSidebarActiveView: (view: SidebarViewType) => {
          set((state) => ({
            sidebar: {
              ...state.sidebar,
              activeView: view,
            },
          }));
        },

        toggleSidebarCollapse: () => {
          set((state) => ({
            sidebar: {
              ...state.sidebar,
              isCollapsed: !state.sidebar.isCollapsed,
            },
          }));
        },

        // 面板操作
        togglePanel: () => {
          set((state) => ({
            panel: {
              ...state.panel,
              isVisible: !state.panel.isVisible,
            },
          }));
        },

        setPanelVisible: (visible: boolean) => {
          set((state) => ({
            panel: {
              ...state.panel,
              isVisible: visible,
            },
          }));
        },

        setPanelPosition: (position: PanelPosition) => {
          set((state) => ({
            panel: {
              ...state.panel,
              position,
            },
          }));
        },

        setPanelHeight: (height: number) => {
          // 限制面板高度在150-500px之间
          const clampedHeight = Math.max(150, Math.min(500, height));
          set((state) => ({
            panel: {
              ...state.panel,
              height: clampedHeight,
            },
          }));
        },

        setPanelWidth: (width: number) => {
          // 限制面板宽度在300-800px之间
          const clampedWidth = Math.max(300, Math.min(800, width));
          set((state) => ({
            panel: {
              ...state.panel,
              width: clampedWidth,
            },
          }));
        },

        setPanelActiveTab: (tab: PanelType) => {
          set((state) => ({
            panel: {
              ...state.panel,
              activeTab: tab,
            },
          }));
        },

        addPanelTab: (tab: PanelType) => {
          set((state) => {
            if (!state.panel.tabs.includes(tab)) {
              return {
                panel: {
                  ...state.panel,
                  tabs: [...state.panel.tabs, tab],
                },
              };
            }
            return state;
          });
        },

        removePanelTab: (tab: PanelType) => {
          set((state) => {
            const newTabs = state.panel.tabs.filter(t => t !== tab);
            return {
              panel: {
                ...state.panel,
                tabs: newTabs,
                activeTab: state.panel.activeTab === tab
                  ? (newTabs[0] || PanelType.Terminal)
                  : state.panel.activeTab,
              },
            };
          });
        },

        // 编辑器操作
        setEditorConfig: (config: Partial<LayoutConfig['editor']>) => {
          set((state) => ({
            editor: {
              ...state.editor,
              ...config,
            },
          }));
        },

        // 主题操作
        setTheme: (theme: Theme) => {
          set((state) => ({
            theme: {
              ...state.theme,
              current: theme,
            },
          }));
        },

        toggleTheme: () => {
          set((state) => {
            const newTheme = state.theme.current === Theme.Light
              ? Theme.Dark
              : Theme.Light;
            return {
              theme: {
                ...state.theme,
                current: newTheme,
              },
            };
          });
        },

        setFollowSystem: (follow: boolean) => {
          set((state) => ({
            theme: {
              ...state.theme,
              followSystem: follow,
            },
          }));
        },

        // 窗口操作
        setWindowConfig: (config: Partial<LayoutConfig['window']>) => {
          set((state) => ({
            window: {
              ...state.window,
              ...config,
            },
          }));
        },

        toggleMaximize: () => {
          set((state) => ({
            window: {
              ...state.window,
              isMaximized: !state.window.isMaximized,
            },
          }));
        },

        toggleFullscreen: () => {
          set((state) => ({
            window: {
              ...state.window,
              isFullscreen: !state.window.isFullscreen,
            },
          }));
        },

        // 工具栏操作
        toggleToolbar: () => {
          set((state) => ({
            toolbar: {
              ...state.toolbar,
              isVisible: !state.toolbar.isVisible,
            },
          }));
        },

        setToolbarItems: (items: string[]) => {
          set((state) => ({
            toolbar: {
              ...state.toolbar,
              items,
            },
          }));
        },

        // 状态栏操作
        toggleStatusBar: () => {
          set((state) => ({
            statusBar: {
              ...state.statusBar,
              isVisible: !state.statusBar.isVisible,
            },
          }));
        },

        setStatusBarItems: (items: string[]) => {
          set((state) => ({
            statusBar: {
              ...state.statusBar,
              items,
            },
          }));
        },

        // 重置布局
        resetLayout: () => {
          set(defaultLayoutConfig);
        },

        // 导入/导出配置
        exportConfig: () => {
          const state = get();
          return {
            sidebar: state.sidebar,
            panel: state.panel,
            editor: state.editor,
            theme: state.theme,
            window: state.window,
            toolbar: state.toolbar,
            statusBar: state.statusBar,
          };
        },

        importConfig: (config: Partial<LayoutConfig>) => {
          set((state) => ({
            ...state,
            ...config,
          }));
        },
      }),
      {
        name: 'codegraph-layout-store',
        version: 1,
        // 只持久化部分配置，窗口状态不持久化
        partialize: (state) => ({
          sidebar: state.sidebar,
          panel: state.panel,
          editor: state.editor,
          theme: state.theme,
          toolbar: state.toolbar,
          statusBar: state.statusBar,
        }),
      }
    )
  )
);

// 主题相关的工具函数
export const applyTheme = (theme: Theme) => {
  const root = document.documentElement;

  if (theme === Theme.Auto) {
    // 跟随系统主题
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    root.classList.toggle('dark', prefersDark);
  } else {
    root.classList.toggle('dark', theme === Theme.Dark);
  }
};

// 监听系统主题变化
export const setupThemeListener = () => {
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

  const handleThemeChange = () => {
    const { theme } = useLayoutStore.getState();
    if (theme.followSystem && theme.current === Theme.Auto) {
      applyTheme(Theme.Auto);
    }
  };

  mediaQuery.addEventListener('change', handleThemeChange);

  return () => {
    mediaQuery.removeEventListener('change', handleThemeChange);
  };
};
